package com.imooc.netty;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;

import java.nio.charset.Charset;

/**
 * @author 朝花不迟暮
 * @version 1.0
 * @date 2020/12/27 19:13
 */
// SimpleChannelInboundHandler: 对于请求来讲，其实相当于[入站，入境]
public class CustomHandler extends SimpleChannelInboundHandler<HttpObject>
{
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, HttpObject msg) throws Exception
    {
        //获取channel
        Channel channel = ctx.channel();
        if (msg instanceof HttpRequest)
        {
            System.out.println(channel.remoteAddress());
            ByteBuf byteBuffer = Unpooled.copiedBuffer("hello~", CharsetUtil.UTF_8);
            //构建一个http response
            DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, byteBuffer);
            // 为响应增加数据类型和长度
            response.headers().add(HttpHeaderNames.CONTENT_TYPE, "text/plain");
            response.headers().add(HttpHeaderNames.CONTENT_LENGTH, byteBuffer.readableBytes());
            ctx.writeAndFlush(response);
        }
    }
}
